package com.cs.service;


import com.cs.mapper.DrugMapper;
import com.cs.pojo.Drug;
import com.cs.pojo.DrugExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class DrugService {
    
    @Resource
    private DrugMapper drugMapper;
    
    @Transactional (propagation = Propagation.REQUIRES_NEW, readOnly = true)
    public Drug queryById(int drId){
        return drugMapper.selectByPrimaryKey(drId);
    }
    
    @Transactional (propagation = Propagation.REQUIRES_NEW, readOnly = true)
    public PageInfo<Drug> queryByPage(Integer pageSize , Integer pageNum , Drug drug){
        
        DrugExample example = new DrugExample();
        DrugExample.Criteria criteria = example.createCriteria();
        
        if (drug != null){
            String drName = drug.getDrName();
            String drType = drug.getDrType();
            
            if (drName != null && !"".equals(drName) && !"null".equals(drName)){
                criteria.andDrNameLike("%"+drName.trim()+"%");
            }
            if (!"0".equals(drType.trim()) && !"".equals(drType)  && !"null".equals(drType)){
                criteria.andDrTypeEqualTo(drType);
            }
        }
        PageHelper.startPage(pageNum , pageSize);
        List<Drug> list = drugMapper.selectByExample(example);
        return new PageInfo<>(list);
    }
    
    @Transactional (propagation = Propagation.REQUIRES_NEW, readOnly = true)
    public List<Drug> queryAll(){
        DrugExample example = new DrugExample();
        DrugExample.Criteria criteria = example.createCriteria();
        return drugMapper.selectByExample(example);
    }
    
    @Transactional (propagation = Propagation.REQUIRED , rollbackFor = {Exception.class})
    public int add(Drug drug){
        return drugMapper.insertSelective(drug);
    }
    
    @Transactional (propagation = Propagation.REQUIRED , rollbackFor = {Exception.class})
    public int del(Integer drId){
        return drugMapper.deleteByPrimaryKey(drId);
    }
    
    @Transactional (propagation = Propagation.REQUIRED , rollbackFor = {Exception.class})
    public int update(Drug drug){
        return drugMapper.updateByPrimaryKeySelective(drug);
    }
    
}
